﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AxIpeDspCtrlLib;
using IpeEngCtrlLib;
using SherlockModel;

namespace MultiSherlockGUI
{
    public partial class GUI : Form
    {
        public delegate void invokeDelegate();

        public GUI()
        {
            InitializeComponent();
        }

        SherlockModelSystem[] m_VisionSystemArray = new SherlockModelSystem[GlobalCfg.m_iSherlockCount];
        AxIpeDspCtrl[] m_AxIpeDspCtrlArray = new AxIpeDspCtrl[GlobalCfg.m_iSherlockCount];

        const int SherlockID_Cam_1 = 0;
        const int SherlockID_Cam_2 = 1;
        const int SherlockID_Cam_3 = 2;
        const int SherlockID_Cam_4 = 3;
        const int SherlockID_Cam_5 = 4;

        bool m_bRuning = false;

        bool InitSherlock()
        {
            m_AxIpeDspCtrlArray[0] = axIpeDspCtrl_Sherlock_0;
            m_AxIpeDspCtrlArray[1] = axIpeDspCtrl_Sherlock_1;
           // m_AxIpeDspCtrlArray[2] = axIpeDspCtrl_Sherlock_2;
          //  m_AxIpeDspCtrlArray[3] = axIpeDspCtrl_Sherlock_3;
          //  m_AxIpeDspCtrlArray[4] = axIpeDspCtrl_Sherlock_4;

            bool bRet = true,bRet_1 = false,bRet_2=  false;
            for (int i=0;i< GlobalCfg.m_iSherlockCount;i++)
            {
                bRet_1 = bRet_2 = true;
                m_VisionSystemArray[i] = new SherlockModelSystem(i);
                if (m_VisionSystemArray[i].CreateVisionSystemEngine(GlobalCfg.m_SherlockCfg[i].strDrivers) != true)
                {
                    bRet_1 = false;
                    bRet = false;
                }

                m_VisionSystemArray[i].SetPicLogParam(GlobalCfg.m_SherlockCfg[i].strPicPath, true,GlobalCfg.m_SherlockCfg[i].bSavePic_OK, GlobalCfg.m_SherlockCfg[i].bSavePic_NG, GlobalCfg.m_SherlockCfg[i].iMaxPicNum, GlobalCfg.m_SherlockCfg[i].iMaxPicLogDay);
                bRet_2 = m_VisionSystemArray[i].InitializeVisionSystemEngine(GlobalCfg.m_SherlockCfg[i].strProgramPath , GlobalCfg.m_SherlockCfg[i].strImgWindowsName, m_AxIpeDspCtrlArray[i]);

                m_VisionSystemArray[i].OnSherlockRunCompleted += OnVisionSystem_RunCompleted;
                m_VisionSystemArray[i].OnSherlockRunStop += OnVisionSystem_RunStop;
                m_VisionSystemArray[i].OnSherlockRunError += OnVisionSystem_RunError;

                //
                m_VisionSystemArray[i].VarSetDouble("dCount_OK",GlobalCfg.m_SherlockCfg[i].eachCheckResult.iCount_OK);
                m_VisionSystemArray[i].VarSetDouble("dCount_NG", GlobalCfg.m_SherlockCfg[i].eachCheckResult.iCount_NG);

                GlobalLog.WriteInfoLog("Start Sherlock: " + GlobalCfg.m_SherlockCfg[i].strProgramPath + "结果：CreateVisionSystemEngine--" + bRet_1 + ",InitializeVisionSystemEngine--" + bRet_2);
            }

            m_bRuning = false;

            return bRet;
        }

        void FinitSherlock()
        {
            m_bRuning = false;

            for (int i = 0; i < GlobalCfg.m_iSherlockCount; i++)
            {
                m_VisionSystemArray[i].Stop();

                m_VisionSystemArray[i].DeleteVisionSystemEngine();
            }

            GlobalLog.WriteInfoLog("Stop Sherlock");
        }


        void OnVisionSystem_RunCompleted(SherlockModelSystem srcSherlockModel, int iID)
        {
            if (srcSherlockModel != null)
            {
                bool bResult = srcSherlockModel.VarGetBool("bRet_Out", false);

                if (bResult == true && srcSherlockModel.bSavePic_OK == true)
                {
                    srcSherlockModel.SaveImage_jpeg("imgA", bResult);
                }
                else if (bResult == false && srcSherlockModel.bSavePic_NG == true)
                {
                    srcSherlockModel.SaveImage_jpeg("imgA", bResult);
                }

                GlobalCfg.m_SherlockCfg[iID].eachCheckResult.iCount_OK = (int)m_VisionSystemArray[iID].VarGetDouble("dCount_OK", 0);
                GlobalCfg.m_SherlockCfg[iID].eachCheckResult.iCount_NG = (int)m_VisionSystemArray[iID].VarGetDouble("dCount_NG",0);

                ShowCheckResult();
            }
           
        }

        void OnVisionSystem_RunStop(SherlockModelSystem srcSherlockModel, int iID)
        {
            m_bRuning = false;

            GlobalLog.WriteErrorLog("Sherlock Stoped: " + GlobalCfg.m_SherlockCfg[iID].strProgramPath);
        }

        void OnVisionSystem_RunError(SherlockModelSystem srcSherlockModel, int iID, I_EXEC_ERROR euMsg)
        {
            bool bState = false;
            string strMsg;
            switch (euMsg)
            {
                case IpeEngCtrlLib.I_EXEC_ERROR.I_EXEC_ROI_OUTSIDE:
                    bState = true;
                    strMsg = "ROI 超出图片范围";
                    break;
                case IpeEngCtrlLib.I_EXEC_ERROR.I_EXEC_UNKNOWN_ERROR:
                    strMsg = "相机出现未知错误，请检查相机是否运行正常，网线是否正常";
                    break;
                case IpeEngCtrlLib.I_EXEC_ERROR.I_EXEC_IO_NOT_CONNECTED:
                    strMsg = "相机I/O没有连接";
                    break;
                case IpeEngCtrlLib.I_EXEC_ERROR.I_EXEC_STOP:
                    strMsg = "相机停止运行";
                    break;
                case IpeEngCtrlLib.I_EXEC_ERROR.I_EXEC_SCRIPT_ERROR:
                    strMsg = "相机程序运行出错";
                    break;
                case IpeEngCtrlLib.I_EXEC_ERROR.I_EXEC_TIMEOUT:
                default:	//I_EXEC_OK	--  --
                    bState = true;
                    strMsg = "相机运行正常";
                    break;
            }

            GlobalLog.WriteErrorLog("VisionSystem_RunError " + srcSherlockModel.m_strSherlockPathName + "  ErrorID " + euMsg);
            if (bState == false)
            {
                if (label_CheckResult.InvokeRequired == true)
                {
                    invokeDelegate del = () =>
                    {
                        label_CheckResult.Text = strMsg;
                        label_CheckResult.BackColor = Color.Yellow;
                    };
                    Invoke(del);
                }
                else
                {
                    label_CheckResult.Text = strMsg;
                    label_CheckResult.BackColor = Color.Yellow;
                }
            }
        }

        private void GUI_Load(object sender, EventArgs e)
        {
            GlobalLog.WriteInfoLog("系统启动");

            GlobalCfg.LoadCfg();
            ShowCheckResult();

            InitSherlock();

            timer_SaveResultCount.Enabled = true;

           if (GlobalCfg.m_SysCfg.bAutoRun == true)
            {
                MenuItem_Start_Click(sender, e);
            }

            EnableAllWindows();
        }

       
        private void GUI_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (MessageBox.Show("退出后，请不能进行检测！！","请确认",MessageBoxButtons.YesNo) == DialogResult.No)
            {
                e.Cancel = true;
                return;
            }

            FinitSherlock();

            GlobalLog.WriteInfoLog("系统退出");
        }


        private void EnableAllWindows()
        {
            bool bEnabled =! m_bRuning;

            MenuItem_RunOnce.Enabled = bEnabled;
            MenuItem_ShowLivePic.Enabled = bEnabled;
            MenuItem_Stop.Enabled = ! bEnabled;
            MenuItem_Start.Enabled = bEnabled;

            if (m_bRuning == false && GlobalCfg.m_UserParam.bLogIn == true)
            {
               MenuItem_SaveSherlock.Enabled = true;
            }
            else
            {
                MenuItem_SaveSherlock.Enabled = false;
            }
        }

        private void MenuItem_LogIn_Click(object sender, EventArgs e)
        {
            LogInDlg dlg = new LogInDlg();
            dlg.ShowDialog();

            if (GlobalCfg.m_UserParam.bLogIn == true)
            {
                GlobalLog.WriteInfoLog("用户登陆" + GlobalCfg.m_UserParam.strUserName);
            }

            EnableAllWindows();
        }

        private void MenuItem_LogOut_Click(object sender, EventArgs e)
        {
            GlobalCfg.m_UserParam.bLogIn = false;

            GlobalLog.WriteInfoLog("用户退出" + GlobalCfg.m_UserParam.strUserName);

           

            EnableAllWindows();
        }

        private void MenuItem_ShowLivePic_Click(object sender, EventArgs e)
        {
            MenuItem_Stop_Click(sender, e);

            MenuItem_ShowLivePic.Checked = !MenuItem_ShowLivePic.Checked;

            if (MenuItem_ShowLivePic.Checked == true)
            {
                for (int i = 0; i < GlobalCfg.m_iSherlockCount; i++)
                {
                    m_VisionSystemArray[i].CamLive();
                }

                GlobalLog.WriteInfoLog("MenuItem_ShowLivePic_Click  -- On");
            }
            else
            {
                for (int i = 0; i < GlobalCfg.m_iSherlockCount; i++)
                {
                    m_VisionSystemArray[i].CamLive("", false);

                    GlobalLog.WriteInfoLog("MenuItem_ShowLivePic_Click --- Off");
                }
                EnableAllWindows();
            }
        }

        private void MenuItem_RunOnce_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < GlobalCfg.m_iSherlockCount; i++)
            {
                m_VisionSystemArray[i].OnceRun();
            }

            GlobalLog.WriteInfoLog("MenuItem_ShowLivePic_Click --- Off");
        }

        private void MenuItem_Start_Click(object sender, EventArgs e)
        {
            //for (int i = 0; i < GlobalCfg.m_iSherlockCount; i++)
            //{
            //    bool bRet = m_VisionSystemArray[i].ContinuousRun();
            //    GlobalLog.WriteInfoLog("MenuItem_Start_Click--" +GlobalCfg.m_SherlockCfg[i].strProgramPath + "      结果：" + bRet);
            //}

            m_bRuning = true;
            EnableAllWindows();
        }

        private void MenuItem_Stop_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < GlobalCfg.m_iSherlockCount; i++)
            {
                m_VisionSystemArray[i].Stop();
            }

            GlobalLog.WriteInfoLog("MenuItem_Stop_Click");

            m_bRuning = false;

            EnableAllWindows();
        }

        private void MenuItem_SaveOKPic_Click(object sender, EventArgs e)
        {
            MenuItem_SaveOKPic.Checked = ! MenuItem_SaveOKPic.Checked;

            for (int i = 0; i < GlobalCfg.m_iSherlockCount; i++)
            {
                m_VisionSystemArray[i].bSavePic_OK = MenuItem_SaveOKPic.Checked;
            }

            GlobalLog.WriteInfoLog("MenuItem_SaveOKPic_Click");
        }

        private void MenuItem_SaveNgPic_Click(object sender, EventArgs e)
        {
            MenuItem_SaveNgPic.Checked = !MenuItem_SaveNgPic.Checked;

            for (int i = 0; i < GlobalCfg.m_iSherlockCount; i++)
            {
                m_VisionSystemArray[i].bSavePic_NG = MenuItem_SaveNgPic.Checked;
            }

            GlobalLog.WriteInfoLog("MenuItem_SaveNgPic_Click");
        }

        private void button_ResetCheckResult_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < GlobalCfg.m_iSherlockCount; i++)
            {
                m_VisionSystemArray[i].VarSetDouble("dCount_OK", 0);
                m_VisionSystemArray[i].VarSetDouble("dCount_NG", 0);

                GlobalCfg.m_SherlockCfg[i].eachCheckResult.iCount_NG = 0;
                GlobalCfg.m_SherlockCfg[i].eachCheckResult.iCount_OK = 0;
            }

            ShowCheckResult();

            GlobalLog.WriteInfoLog("button_ResetCheckResult_Click");
        }

        private void ShowCheckResult()
        {
            int iOK = 0, iNG = 0;
            for (int i = 0; i < GlobalCfg.m_iSherlockCount; i++)
            {
                iOK += GlobalCfg.m_SherlockCfg[i].eachCheckResult.iCount_OK;
                iNG += GlobalCfg.m_SherlockCfg[i].eachCheckResult.iCount_NG;
            }

            double dTotal = iOK + iNG;
            double dPassPersent = 0;

            if (dTotal > 0)
            {
                dPassPersent = iOK * 100 / dTotal;
            }
            else
            {
                dPassPersent = 0;
            }

            if (textBox_CheckCount_NG.InvokeRequired == true)
            {
                invokeDelegate del = () =>
                {
                    textBox_CheckCount_OK.Text = iOK.ToString();
                    textBox_CheckCount_NG.Text = iNG.ToString();
                    textBox_CheckCount_Total.Text = dTotal.ToString();
                    textBox_CheckPersent_OK.Text = dPassPersent.ToString("F2" ) + "%";
                };
                Invoke(del);
            }
            else
            {
                textBox_CheckCount_OK.Text = iOK.ToString();
                textBox_CheckCount_NG.Text = iNG.ToString();
                textBox_CheckCount_Total.Text = dTotal.ToString();
                textBox_CheckPersent_OK.Text = dPassPersent.ToString("F2") + "%";
            }
        }

        private void timer_SaveResultCount_Tick(object sender, EventArgs e)
        {
            GlobalCfg.SaveCheckResult(textBox_CheckCount_OK.Text, textBox_CheckCount_NG.Text);
        }

        private void MenuItem_SaveSherlock_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < GlobalCfg.m_iSherlockCount; i++)
            {
                m_VisionSystemArray[i].SaveIVS();
            }

            GlobalLog.WriteInfoLog("MenuItem_SaveSherlock_Click");
        }

        private void button_CfgRoi_Top_Click(object sender, EventArgs e)
        {
            string strRoi = "RectA";

            strRoi += ".Search - Edge";
            for (int i = 0; i < GlobalCfg.m_iSherlockCount; i++)
            {

                m_VisionSystemArray[i].m_Engine.InstrCommand(strRoi, (int)I_INSTR_COMMANDS.INSTR_SHOW_PARMS_DLG, 0);
            }
        }
    }
}
